package com.flyox.game.militarychess.server.minaserver;

import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flyox.game.militarychess.CONSTS;
import com.flyox.game.militarychess.message.ChessPackage;
import com.flyox.game.militarychess.server.business.HelloService;
import com.flyox.game.militarychess.server.business.RequestService;
import com.flyox.game.militarychess.server.services.PlayerService;

public class MinaServerHandler extends IoHandlerAdapter {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	public void sessionCreated(IoSession session) {
	}

	public void sessionOpened(IoSession session) {
	}

	public void sessionClosed(IoSession session) {
		String pID=(String)session.getAttribute(CONSTS.SYS_SESSION_PLAYERID);
		PlayerService playerService=new PlayerService();
		playerService.removePlayer(pID);
	}

	public void sessionIdle(IoSession session, IdleStatus status) {
	}

	public void exceptionCaught(IoSession session, Throwable cause) {
		if (logger.isWarnEnabled()) {
			logger.warn("EXCEPTION, please implement " + getClass().getName() + ".exceptionCaught() for proper handling:", cause);
		}
	}

	public void messageReceived(IoSession session, Object message) throws Exception {
		ChessPackage chessPackage = (ChessPackage) message;
		switch (chessPackage.getCmd()){
		case CONSTS.CMD_HELLO:
			new HelloService().processHello(session);
			break;
		case CONSTS.CMD_HAND_1:
			new HelloService().processHand1(session,chessPackage.getPlayerID());
			break;
		case CONSTS.CMD_HAND_2:
			new HelloService().processHand2(session,chessPackage.getPlayerID(),chessPackage.getContent());
			break;
		case CONSTS.CMD_SEC:
			new RequestService().processSec(session,chessPackage.getPlayerID(),chessPackage.getContent());
			break;
		case CONSTS.CMD_MANAGER:
			new RequestService().processManager(session,chessPackage.getContent());
			break;
		default:
			//error
			break;
		}
	}

	public void messageSent(IoSession session, Object message) {

	}
}
